package com.newcoder.community.controller;

import com.newcoder.community.entity.Page;
import com.newcoder.community.pojo.DiscussPost;
import com.newcoder.community.pojo.User;
import com.newcoder.community.serverce.DiscussPostServiceImpl;
import com.newcoder.community.serverce.LikeService;
import com.newcoder.community.serverce.UserServiceImpl;
import com.newcoder.community.utill.CommunityConstant;
import com.newcoder.community.utill.CommunityUtill;
import com.newcoder.community.utill.RedisKeyUtill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {
    @Autowired
    DiscussPostServiceImpl discussPostService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    private LikeService likeService;

    @GetMapping("/index")
    public String getIndexPage(Model model, Page page) {
        page.setPath("/index");
        page.setRows(discussPostService.selectDiscussPostRows(0));
        List<DiscussPost> list = discussPostService.selectDiscussPosts(0, page.getOffset(), page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost discussPost : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", discussPost);
                User user = userService.selectById(discussPost.getUserId());
                map.put("user", user);
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
                map.put("likeCount",likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        return "/index";
    }

    @RequestMapping
    public String toError() {
        return "/error/500";

    }
}
